package com.lc.hongtai.fragment;

import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.lc.hongtai.MyApplication;
import com.lc.hongtai.R;
import com.lc.hongtai.adapter.Fourth_findAdapter2;
import com.lc.hongtai.conn.JsonAccessToken;
import com.lc.hongtai.conn.JsonInterest;
import com.lc.hongtai.toast.LovelyToast;
import com.lc.hongtai.view.FullyLinearLayoutManager;
import com.lc.hongtai.view.SimpleDividerItemDecoration;
import com.zcx.helper.activity.AppV4Fragment;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.bound.BoundViewHelper;
import com.zcx.helper.http.AsyCallBack;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrClassicDefaultHeader;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.PtrUIHandler;
import in.srain.cube.views.ptr.indicator.PtrIndicator;


/**
 * Created by Administrator on 2016/4/17.
 */
@SuppressLint("ValidFragment")
public class ProductDetailFragment extends AppV4Fragment {


    String url;
    private RecyclerView.Adapter mAdapter;
    private FullyLinearLayoutManager mLayoutManager;

    private RecyclerView rv01;

    private PtrFrameLayout store_house_ptr_frame;
    private PtrClassicDefaultHeader header;

    public int nowPage = 1;
    public int totalPages = 1;
    public int pageSize = 0;
    public int totalRows = 0;

    private boolean canLoadMore = true;



    public List<JsonInterest.Info.ListContent> list = new ArrayList<>();

    Fourth_findAdapter2 mAdapter2;


    @BoundView(R.id.regist_web_wv)
    WebView regist_web_wv;


    public static ProductDetailFragment getInstance(String url) {
        ProductDetailFragment sf = new ProductDetailFragment();
        sf.url = url;
        return sf;
    }



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//        View view = inflater.inflate(R.layout.fr_simple_card, null);
        View view = BoundViewHelper.boundView(this, MyApplication.scaleScreenHelper.loadView((ViewGroup) inflater.inflate(R.layout.fragment_product, null)));
        ButterKnife.bind(getActivity());

        rv01 = (RecyclerView) view.findViewById(R.id.rv_01);
        rv01.setLayoutManager(new LinearLayoutManager(getActivity()));

        //rv01.setAdapter(mAdapter = new Fourth_findAdapter(getActivity(),mDatas));

//        mAdapter2 = new Fourth_findAdapter2(getActivity(), mDatas2);
//
//        mAdapter = new NewJiaXiAdapter(getActivity(), mDatas);

        rv01.setAdapter(mAdapter);
        // rv01.setAdapter(mAdapter = new JIaxiAdapter(getActivity(), mDatas));

        initView(view);
        initRefreshListener();
        //  getAccessToken(true,nowPage);
        WebSettings webSettings = regist_web_wv.getSettings();
        webSettings.setJavaScriptEnabled(true);
// 若加载的 html 里有JS 在执行动画等操作，会造成资源浪费（CPU、电量）
// 在 onStop 和 onResume 里分别把 setJavaScriptEnabled() 给设置成 false 和 true 即可

//支持插件


//设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

//缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件

//其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
   // url=getIntent().getStringExtra("url");
        regist_web_wv.loadUrl(url);
        return view;
    }


    private void initView(View view) {
        this.rv01 = (RecyclerView) view.findViewById(R.id.rv_01);
        //    this.ivback = (ImageView)  view.findViewById(R.id.iv_back);
        this.store_house_ptr_frame = (PtrFrameLayout) view.findViewById(R.id.store_house_ptr_frame);
        mLayoutManager = new FullyLinearLayoutManager(getActivity());
        header = new PtrClassicDefaultHeader(getActivity());
        store_house_ptr_frame.setHeaderView(header);
        rv01.setLayoutManager(mLayoutManager);
        // specify an adapter (see also next example)
        Drawable drawable = ContextCompat.getDrawable(getActivity(), R.drawable.line_divider3);
        rv01.addItemDecoration(new SimpleDividerItemDecoration(getActivity(), drawable, 40));

    }

    private void initRefreshListener() {
        rv01.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItemPosition = ((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition();
                if (dy > 0 && canLoadMore && lastVisibleItemPosition + 1 == mAdapter.getItemCount()) {
                    canLoadMore = false;
                    if (nowPage < totalPages) {
                        //getAccessToken(true, nowPage + 1);
                    } else {
                        //UtilToast.show(InvestManageDetailActivity.this, "当前页已是最后一页");
                    }
                }
            }
        });

        store_house_ptr_frame.setPtrHandler(new PtrHandler() {


            /*@Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                int firstVisibleItemPosition = ((LinearLayoutManager) mLayoutManager).findFirstCompletelyVisibleItemPosition();
               // return firstVisibleItemPosition == 0 || mDatas.size() == 0;
            }*/

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return false;
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //   list.clear();
              /*  nowPage = 1;
                getAccessToken(false, nowPage);*/
            }
        });
        store_house_ptr_frame.addPtrUIHandler(new PtrUIHandler() {
            @Override
            public void onUIReset(PtrFrameLayout frame) {
                header.onUIReset(frame);
            }

            @Override
            public void onUIRefreshPrepare(PtrFrameLayout frame) {
                header.onUIRefreshPrepare(frame);
            }

            @Override
            public void onUIRefreshBegin(PtrFrameLayout frame) {
                header.onUIRefreshBegin(frame);
            }

            @Override
            public void onUIRefreshComplete(PtrFrameLayout frame) {
                header.onUIRefreshComplete(frame);
            }

            @Override
            public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
                header.onUIPositionChange(frame, isUnderTouch, status, ptrIndicator);
            }
        });
    }



    private void getAccessToken() {
        new JsonAccessToken("index/invest_detail", new AsyCallBack<JsonAccessToken.Info>() {
            @Override
            public void onSuccess(String toast, int type, JsonAccessToken.Info info) throws Exception {
                if (info != null) {
                    if (!TextUtils.isEmpty(info.access_token)) {
                        initData(info.access_token);
                    } else {
                        // UtilToast.show(InvestmentActivity.this, "安全验证失败！");
                        LovelyToast.makeText(getActivity(), "安全验证失败", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                    }
                }
            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                // UtilToast.show(InvestmentActivity.this, "安全验证失败！");
                LovelyToast.makeText(getActivity(), "安全验证失败", 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
            }
        }).execute(getActivity(), true);

    }


    private void initData(String access_token) {
      /*  new JsonInvestdetail(access_token, getIntent().getStringExtra("id"), "detail", new AsyCallBack<JsonInvestdetail.Info>() {
            @Override
            public void onSuccess(String toast, int type, JsonInvestdetail.Info info) throws Exception {
                if (info != null) {


                } else {
                    // UtilToast.show(InvestmentActivity.this, JsonInvestdetail.TOAST);
                    LovelyToast.makeText(getActivity(), JsonInvestdetail.TOAST, 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                }
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {

            }

        }).execute(getActivity(), false);*/
    }


}
